<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <!-- gutter可以增加间距 -->
      <el-row :gutter="20">
        <!-- :span表示占有多宽 -->
        <el-col :span="7">
          <div class="grid-content bg-purple">
            <div slot="header" class="clearfix">
              <!-- 搜索框 input绑定query  button等于重新获取表单 clear重新获取-->
              <el-input
                placeholder="请输入内容"
                class="input-with-select"
                v-model="queryInfo.query"
                clearable
                clear="getUserList"
              >
                <el-button slot="append" @click="getUserList" icon="el-icon-search"></el-button>
              </el-input>
            </div>
          </div>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible=true" round>添加用户</el-button>
        </el-col>
      </el-row>
      <el-table :data="userlist" style="width: 100%" border>
        <!-- 索引列 -->
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="username" label="姓名" width="180"></el-table-column>
        <el-table-column prop="email" label="邮箱" width="180"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column prop label="状态">
          <!-- 记不得slot scope的话去看作用域插槽的用法 -->
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="userStateChanged(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <!--tooltip content为鼠标移在上面显示的 -->
        <el-table-column prop label="操作">
          <template slot-scope="scope">
            <el-button
              type="primary"
              content="修改"
              icon="el-icon-edit"
              @click="showEidtDialog(scope.row.id)"
            >修改</el-button>
            <el-button
              @click="removeUserById(scope.row.id)"
              type="danger"
              content="删除"
              icon="el-icon-delete"
            >删除</el-button>
            <el-tooltip class="item" effect="dark" content="分配角色" enterable placement="top-start">
              <el-button type="warning" icon="el-icon-setting" @click="setRole(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="400"
      ></el-pagination>
    </el-card>
    <!-- 添加用户的对话框 -->
    <el-dialog title="添加用户" :visible.sync="addDialogVisible" @close="addDialogClosed" width="30%">
      <!-- 内容主体区 -->
      <el-form :model="addForm" :rules="addFormRules" label-width="70px" ref="addFormRef">
        <el-form-item label="用户名" prop="username">
          <!-- prop具体校验规则 -->
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加用户的对话框 -->
    <el-dialog title="修改用户" @close="editDialogClose" :visible.sync="editDialogVisible" width="30%">
      <!-- 内容主体区 -->
      <el-form :model="editForm" :rules="addFormRules" label-width="70px" ref="editFormRef">
        <el-form-item label="用户名" prop="username">
          <!-- prop具体校验规则 -->
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="分配角色"
      @close="setRoleDialogClose"
      :visible.sync="setRoleDialogVisible"
      width="30%"
    >
      <!-- 内容主体区 -->
      <p>用户:{{userInfo.username}}</p>
      <p>角色:{{userInfo.role_name}}</p>
      选择角色：<el-select v-model="selectedRoleId" placeholder="请选择">
        <el-option
          v-for="item in rolesList"
          :key="item.id"
          :label="item.roleName"
          :value="item.id"
        ></el-option>
      </el-select>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleInfo()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    var checkEmail = (rule, value, cb) => {
      const regEmail = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
      if (regEmail.test(value)) {
        return cb()
      } else {
        return cb(new Error('请输入合法的邮箱！'))
      }
    }
    return {
      // 获取用户列表的参数对象
      queryInfo: {
        query: '',
        // 当前的页数
        pagenum: 1,
        // 当前每页显示多少条数据
        pagesize: 2
      },
      //后端获取的userlist
      userlist: [],
      total: 0,

      //对话框的显示
      addDialogVisible: false,
      editDialogVisible: false,
      //需要添加的新用户
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      addFormRules: {
        username: { required: true, message: '请输入用户名', trigger: 'blur' },
        password: { required: true, message: '请输入密码', trigger: 'blur' },
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, message: '邮箱不正确！', trigger: 'blur' }
        ],
        mobile: { required: true, message: '请输入移动电话', trigger: 'blur' }
      },
      //接收后端返回的
      editForm: {},

      //第三个对话框按钮
      setRoleDialogVisible: false,
      //需要被分配角色的用户信息
      userInfo: {},
      //所有的角色列表
      rolesList: [],
      //option选中的值
      selectedRoleId:'',
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    //创建时候获取列表
    async getUserList() {
      const { data: res } = await this.$http.get('users', {
        params: this.queryInfo
      })

      if (res.meta.status !== 200) {
        return this.$message.error('获取用户列表失败！')
      }
      this.userlist = res.data.users
      this.total = res.data.total
    },
    //监听事件底下页码的事件
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize
      this.getUserList()
    },
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage
      this.getUserList()
    },
    //监听switch开关的改变,修改 用户的状态
    async userStateChanged(userinfo) {
      const { data: res } = await this.$http.put(
        `users/${userinfo.id}/state/${userinfo.mg_state}`
      )
      if (res.meta.status != 200) {
        userinfo.mg_state = !userinfo.mg_state //更新失败
        return this.$message.error('更新状态失败！')
      } else {
        return this.$message.success('状态更新成功')
      }
    },
    //监听添加用户对话框的关闭事件 关闭后清除input中的内容
    addDialogClosed() {
      this.$refs.addFormRef.resetFields()
    },
    //添加新用户
    addUser() {
      //先判断是否能够发送请求  valid为验证是否通过
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return this.$message.error('用户添加失败')
        const { data: res } = await this.$http.post('users', this.addForm)
        if (res.meta.status != 200) {
          this.$message.error('用户添加失败')
        }
        this.$message.success('添加用户成功')
        this.addDialogVisible = false //关闭对话框
        this.getUserList() //重新获取列表数据
      })
    },
    //点击修改按钮打开对话框并获取信息
    async showEidtDialog(id) {
      const { data: res } = await this.$http.get('users/' + id)
      if (res.meta.status != 200) {
        return this.$message.error('获取用户信息失败')
      } else {
        this.editForm = res.data
      }
      this.editDialogVisible = true
    },
    //修改用户对话框的关闭事件
    editDialogClose() {
      this.$refs.editFormRef.resetFields()
    },
    //提交修改信息
    editUserInfo() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put(
          'users/' + this.editForm.id,
          {
            email: this.editForm.email,
            mobile: this.editForm.mobile
          }
        )
        if (res.meta.status != 200) {
          this.$message.error('信息修改失败！')
        } else {
          //关闭窗口
          this.editDialogVisible = false
          this.$message.success('信息修改成功！')
          //刷新列表
          this.getUserList()
        }
      })
    },
    removeUserById(id) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const { data: res } = await this.$http.delete('users/' + id)
          if (res.meta.status != 200) {
            this.$message.error('删除失败！')
          }
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.getUserList()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    //给y用户分配角色
    async setRole(userinfo) {
      this.userInfo = userinfo
      const { data: res } = await this.$http.get('/roles')
      if (res.meta.status !== 200) {
        return this.$message.error('失败！')
      }
      // console.log(res);
      this.rolesList=res.data
      this.setRoleDialogVisible = true
    },
    //分配角色对话框关闭
    setRoleDialogClose() {
      this.selectedRoleId=''
      this.userInfo=''
    },
    //点击确定按钮，分配角色 1.3.7
    async saveRoleInfo(){
      if(!this.selectedRoleId){
        return this.$message.error("请选择要分配的角色")
      }
      const {data:res}=await this.$http.put(`users/${this.userInfo.id}/role`,{
        rid:this.selectedRoleId
      })
      if(res.meta.status!=200){
        return this.$message.error('更新角色失败！')
      }
      this.$message.success('更新角色成功！')
      this.getUserList()
      this.setRoleDialogVisible=false


    }
  }
  //添加用户对话框的显示和隐藏
}
</script>

<style lang="less" scoped>
.el-pagination {
  margin-top: 10px;
}
</style>